<?php

namespace common\models\notice;

use common\components\wechat\MpWechat;
use common\logics\UserLogic;
use common\models\BaseUser;
use common\models\user\User;
use common\traits\relation\UserData;
use Yii;

/**
 * This is the model class for table "{{%notice_commit}}".
 *
 * @property int $id
 * @property int $notice_id 通告ID
 * @property int $user_id 动态ID
 * @property int $comment_id 评论ID
 * @property int $reply_id 回复ID
 * @property string $body 评论内容
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property UserLogic $user
 */
class NoticeCommit extends \common\db\ActiveRecord
{
    use \common\traits\relation\UserData;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%notice_commit}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['notice_id', 'user_id', 'comment_id', 'reply_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['notice_id', 'body'], 'required'],
            [['body'], 'string', 'max' => 255],
            ['body', 'validateBody'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'notice_id' => '通告ID',
            'user_id' => '动态ID',
            'comment_id' => '评论ID',
            'reply_id' => '回复ID',
            'body' => '评论内容',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function validateBody($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        /* @var $wechat MpWechat */
        $wechat = Yii::$app->get('wechat');
        $return = $wechat->msgSecCheck($this->body);
        if (is_array($return) && array_key_exists('code', $return) && array_key_exists('msg', $return) && $return['code'] == 87014) {
            $this->addError($attribute, $return['msg']);
        }
    }

    public function getReplyuser()
    {
        return $this->hasOne(BaseUser::class, ['id' => 'user_id'])->via('reply')->select('nickname')->column();
    }

    public function getReply()
    {
        return $this->hasOne(NoticeCommit::class, ['id' => 'reply_id']);
    }

    public function fields()
    {
        return [
            'id',
            'user' => 'userText',
            'replyuser',
            'body',
            'status',
            'created_at',
        ];
    }
}
